﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThuVien;

namespace TranTekBE.Check_Revenue
{
    public partial class Check_Revenue : PageRequireLogin
    {

        private int PageCount
        {
            set
            {
                ViewState["PageCount"] = value;
            }
            get
            {
                return FunctionsUtils.ConvertToInt(ViewState["PageCount"], 1);
            }
        }

        //public string JsonString = null;

        

        protected void Page_Load(object sender, EventArgs e)
        {
            
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);
            this.Page.Form.DefaultButton = btnSearch.UniqueID;
            //if (UserInfo.Admin == true)
            //{
                ViewState["DatasChart"] = DrawChart();
                if (Page.IsPostBack == false)
                {

                    this.GetListPageSize(ddlPageSize);
                    GetDllStore();
                    this.LoadData();

                   
                }
            //}
        }
        private void LoadData()
        {
            //if (UserInfo.Admin == false)
            //{
            //    ltError.Text = "Bạn không đủ quyền để xem chức năng này !";
            //    return;
            //}

            ltError.Text = string.Empty;
            try
            {
                int currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                int pageSize = FunctionsUtils.ConvertToInt(ddlPageSize.SelectedValue, FunctionsUtils.ConvertToInt(FunctionsUtils.GetConfigValue("PageSize"), 50));

                string sSearchStore = this.CreateSearchConditionStore();
                string sSearchDatetime = this.CreateSearchConditionDatetime();
                string sSortBy = this.SortBy();

               

                string sql = @"
                                SELECT C007001 as Stores , SUM(C003108) AS TotalRevenue
                                FROM (
                                 select tbCuaHang.C007001  , tbDoanhSo.C003108 from T0070 tbCuaHang
	                             left join  T0031 tbDoanhSo
	                            on tbCuaHang.C007001 = (select SUBSTRING(C003100, 1,CHARINDEX('-',C003100) - 1))
	                           " + sSearchDatetime + @"
   
                                ) TongHop  " + sSearchStore + @"
                                GROUP BY C007001 " + sSortBy;
                // ORDER BY TotalRevenue desc"



                //if (ddlStore.SelectedIndex != 0)
                //    sql = sql + " and C007001 = '" + ddlStore.SelectedValue + "'";

                //sql += " order by C007001 " + ddlSortDirect.SelectedValue;

                DataSet ds = FunctionsUtils.Database.ExecuteQuery(sql);





                //get Total Record de tinh page count
                //DataSet ds1 = FunctionsUtils.Database.ExecuteQuery(sSearch);

                //int pageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                //this.PageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                //ds1.Dispose();
                //int recordCount = FunctionsUtils.ConvertToInt(ds.Tables[0].Rows[0]["NoOfRec"], 0);
                int recordCount = FunctionsUtils.ConvertToInt(ds.Tables[0].Rows.Count, 0);
                this.PageCount = FunctionsUtils.PageCount(recordCount, pageSize);

                currPage = FunctionsUtils.GetCurrPage(currPage, this.PageCount);
                ltPage.Text = string.Format("&nbsp;{0} of {1}&nbsp;", currPage, this.PageCount);
                txtGoPage.Text = currPage.ToString();

                SetButtonPageNavigationStatus(currPage, this.PageCount);

                //DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch, currPage, pageSize);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    rpRevenue.DataSource = ds.Tables[0];
                    rpRevenue.DataBind();
                    ltNoRecord.Visible = false;

                    if (this.PageCount == 1)
                    {
                        phPageNavigation.Visible = false;
                    }
                    else
                    {
                        phPageNavigation.Visible = true;
                    }
                }
                else
                {
                    rpRevenue.DataSource = null;
                    rpRevenue.DataBind();
                    ltNoRecord.Visible = true;
                    phPageNavigation.Visible = false;
                }

                if (ViewState["TCDoanThu"] != null && ViewState["TCDoanThu"].ToString().Length > 0)
                    ltlTongCong.Text = "<b>" + FunctionsUtils.ConvertMoneyVND(ViewState["TCDoanThu"].ToString()) + "</b>";
                else
                    ltlTongCong.Text = "<b>0</b>";

                if (ViewState["TCSoGiaoDich"] != null && ViewState["TCSoGiaoDich"].ToString().Length > 0)
                    ltlTongCongSoGiaoDich.Text = "<b>" + FunctionsUtils.ConvertMoneyVND(ViewState["TCSoGiaoDich"].ToString()) + "</b>";
                else
                    ltlTongCongSoGiaoDich.Text = "<b>0</b>";

                ViewState["TCDoanThu"] = "0";
                ViewState["TCSoGiaoDich"] = "0";
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                //log.WriteLog("Error in ProductMgmt (LoadProducts): {0} {1}", ex, ex.StackTrace);
            }
        }
        private void GetDllStore()
        {
            //DataSet ds = FunctionsUtils.Database.ExecuteQuery("select C007000 as IDCuaHang ,C007001 as CuaHang from T0070  where C007001 not in ('RACHMIEU','PMT')");
            //FunctionsUtils.BindDataForControlList(ddlStore, ds, "CuaHang", "CuaHang", "", "Chọn hết");
            FunctionsUtils.GetDllStore(ddlStore);
        }



        protected void btnClearSearch_Click(object sender, ImageClickEventArgs e)
        {

            txtStoreName.Text = string.Empty;
            this.LoadData();
        }

        private void SetButtonPageNavigationStatus(int currPage, int pageCount)
        {
            if (currPage == 1)
            {
                btnPrev.Enabled = false;
            }
            else
            {
                btnPrev.Enabled = true;
            }

            if (currPage == pageCount)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
            }
        }

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            LoadData();
        }


        protected void Sort_Click(object sender, EventArgs e)
        {
            LinkButton lbt = sender as LinkButton;

            string CommandArgument = string.Empty;
            string css = string.Empty;
            if (lbt.CommandArgument.ToUpper() == "DESC")
            {
                CommandArgument = "ASC";
                css = "sortAsc";
            }
            else
            {
                CommandArgument = "DESC";
                css = "sortDesc";
            }
            

            //remove sort o cac link button khac
            this.RemoveSortCss();

            lbt.CommandArgument = CommandArgument;
            lbt.CssClass = "GridHeader " + css;
            //this.SortBy = lbt.CommandName;
            //this.SortDirect = CommandArgument;

            FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
            FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);

            LoadData();
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            if (txtFrom.Text.Trim().Length == 0 || txtTo.Text.Trim().Length == 0)
                ltError.Text = "Xin vui lòng nhập ngày bắt đầu và ngày kết thúc!";
            else if (Convert.ToDateTime(txtFrom.Text.Trim()) > Convert.ToDateTime(txtTo.Text.Trim()))
                ltError.Text = "Ngày bắt đầu phải bé hơn hoặc bằng ngày kết thúc !";

            LoadData();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ddlSortDirect_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ddlSortBy_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ControlClick_Command(object sender, CommandEventArgs e)
        {
            int currPage = 0;
            switch (e.CommandName)
            {

                case "Sort":
                    //remove sort o cac link button khac
                    this.RemoveSortCss();

                    //FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
                    //FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);
                    // this.SetSortAtributeForLinkButton(ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);
                    // this.LoadData();
                    break;
                case "GoToPage":
                    this.LoadData();
                    break;
                case "GoToPrev":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                    if (currPage > 1)
                    {
                        currPage -= 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadData();
                    break;
                case "GoToNext":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);

                    if (currPage < this.PageCount)
                    {
                        currPage += 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadData();
                    break;
            }
        }

        public string GetDate()
        {
            if (txtFrom.Text == txtTo.Text)
                return txtFrom.Text;
            else
                return txtFrom.Text + " - " + txtTo.Text;
        }

        public string GetNumOfTransaction(object StoreName)
        {

            string sql = @"select COUNT(*) as SoLanGiaoDich from (
	                            select  C003101 from T0031 where C003100 like '{0}%'
	                            and  UC00001 >= convert(datetime,'{1} 00:00:00.001')
	                            and UC00001 <= convert(datetime,'{2} 23:59:59.999')
	                            group by C003101
                            ) RecordSoLanGiaoDich";
            if (ddlLoaiXem.SelectedValue == "")
            {
                ltlDuLieuTu.Text = " ngày hôm nay.";
                sql = string.Format(sql, StoreName.ToString(), txtFrom.Text, txtTo.Text);
            }
            else if (ddlLoaiXem.SelectedValue == "today")
            {
                ltlDuLieuTu.Text = " ngày hôm nay.";
                sql = string.Format(sql, StoreName.ToString(), DateTime.Now.ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastDay")
            {
                ltlDuLieuTu.Text = " ngày hôm qua " + DateTime.Now.AddDays(-1).ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), DateTime.Now.AddDays(-1).ToShortDateString(), DateTime.Now.AddDays(-1).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowWeek")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_SunDayOfWeek(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_SunDayOfWeek(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastWeek")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_SunDayOfWeek(false).ToShortDateString() + " đến ngày " + getLastOrNow_SunDayOfWeek(false).AddDays(6).ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_SunDayOfWeek(false).ToShortDateString(), getLastOrNow_SunDayOfWeek(false).AddDays(6).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowMonth")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Month(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_Month(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastMonth")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Month(false).ToShortDateString() + " đến ngày " + getLastOrNow_Month(false).AddMonths(1).AddDays(-1).ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_Month(false).ToShortDateString(), getLastOrNow_Month(false).AddMonths(1).AddDays(-1).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowYear")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Year(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_Year(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastYear")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Year(false).ToShortDateString() + " đến ngày " + getLastOrNow_Year(false).AddYears(1).AddDays(-1).ToShortDateString();
                sql = string.Format(sql, StoreName.ToString(), getLastOrNow_Year(false).ToShortDateString(), getLastOrNow_Year(false).AddYears(1).AddDays(-1).ToShortDateString());
            }

            DataSet ds = FunctionsUtils.Database.ExecuteQuery(sql);
            if (!FunctionsUtils.IsEmpty(ds))
            {
                if (ViewState["TCSoGiaoDich"] != null && ViewState["TCSoGiaoDich"].ToString().Length > 0)
                    ViewState["TCSoGiaoDich"] = FunctionsUtils.ConvertToDouble(ViewState["TCSoGiaoDich"], 0) + FunctionsUtils.ConvertToDouble(ds.Tables[0].Rows[0]["SoLanGiaoDich"].ToString(), 0);
                else
                    ViewState["TCSoGiaoDich"] = ds.Tables[0].Rows[0]["SoLanGiaoDich"].ToString();
                //return FunctionsUtils.ConvertMoneyVND(ds.Tables[0].Rows[0]["SoLanGiaoDich"].ToString());

                return ds.Tables[0].Rows[0]["SoLanGiaoDich"].ToString();
            }
            else
                return "0";
        }

        public string GetRevenus(object value)
        {

            if (ViewState["TCDoanThu"] != null && ViewState["TCDoanThu"].ToString().Length > 0)
                ViewState["TCDoanThu"] = FunctionsUtils.ConvertToDouble(ViewState["TCDoanThu"], 0) + FunctionsUtils.ConvertToDouble(value, 0);
            else
                ViewState["TCDoanThu"] = value;
            return FunctionsUtils.ConvertMoneyVND(value);
        }



        protected void ddlLoaiXem_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlLoaiXem.SelectedValue == "")
            {
                txtFrom.Enabled = true;
                txtTo.Enabled = true;
                txtFrom.Text = DateTime.Now.ToShortDateString();
                txtTo.Text = DateTime.Now.ToShortDateString();
            }
            else
            {
                txtFrom.Enabled = false;
                txtTo.Enabled = false;
                txtFrom.Text = null;
                txtTo.Text = null;
            }
            LoadData();
        }

        private string CreateSearchConditionStore()
        {

            string sSearch = null;

            if (txtStoreName.Text.Trim().Length > 0)
            {
                sSearch = null;
                sSearch += string.Format(" where C007001 like '%{0}%' ", txtStoreName.Text.Trim());
            }
            if (ddlStore.SelectedValue.Length > 0)
            {
                sSearch = null;
                sSearch += string.Format(" where C007001 like '%{0}%' ", ddlStore.SelectedValue);
            }


            return sSearch;
        }
        private string CreateSearchConditionDatetime()
        {
            string searchDateTime = @"
                        where tbDoanhSo.UC00001 >= convert(datetime,'{0}  00:00:00.001')
                                and 
                        tbDoanhSo.UC00001 < = convert(datetime,'{1} 23:59:59.999')";


            if (ddlLoaiXem.SelectedValue == "")
            {
                searchDateTime = string.Format(searchDateTime, txtFrom.Text, txtTo.Text);
            }

                 //<asp:ListItem Selected="True" Text="Ngày hôm nay" Value="today"></asp:ListItem>
            //                           <asp:ListItem  Text="Ngày hôm qua" Value="lastDay"></asp:ListItem>
            //                           <asp:ListItem  Text="Tuần này" Value="nowWeek"></asp:ListItem>
            //                           <asp:ListItem  Text="Tuần trước" Value="lastWeek"></asp:ListItem>
            //                           <asp:ListItem  Text="Tháng này" Value="nowMonth"></asp:ListItem>
            //                           <asp:ListItem  Text="Tháng trước" Value="lastMonth"></asp:ListItem>
            //                           <asp:ListItem  Text="Năm nay" Value="nowYear"></asp:ListItem>
            //                           <asp:ListItem  Text="Năm trước" Value="lastYear"></asp:ListItem>



            else if (ddlLoaiXem.SelectedValue == "today")
            {
                ltlDuLieuTu.Text = " ngày hôm nay.";
                searchDateTime = string.Format(searchDateTime, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastDay")
            {
                ltlDuLieuTu.Text = " ngày hôm qua " + DateTime.Now.AddDays(-1).ToShortDateString();
                searchDateTime = string.Format(searchDateTime, DateTime.Now.AddDays(-1).ToShortDateString(), DateTime.Now.AddDays(-1).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowWeek")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_SunDayOfWeek(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_SunDayOfWeek(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastWeek")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_SunDayOfWeek(false).ToShortDateString() + " đến ngày " + getLastOrNow_SunDayOfWeek(false).AddDays(6).ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_SunDayOfWeek(false).ToShortDateString(), getLastOrNow_SunDayOfWeek(false).AddDays(6).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowMonth")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Month(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_Month(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastMonth")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Month(false).ToShortDateString() + " đến ngày " + getLastOrNow_Month(false).AddMonths(1).AddDays(-1).ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_Month(false).ToShortDateString(), getLastOrNow_Month(false).AddMonths(1).AddDays(-1).ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "nowYear")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Year(true).ToShortDateString() + " đến ngày " + DateTime.Now.ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_Year(true).ToShortDateString(), DateTime.Now.ToShortDateString());
            }
            else if (ddlLoaiXem.SelectedValue == "lastYear")
            {
                ltlDuLieuTu.Text = " từ ngày " + getLastOrNow_Year(false).ToShortDateString() + " đến ngày " + getLastOrNow_Year(false).AddYears(1).AddDays(-1).ToShortDateString();
                searchDateTime = string.Format(searchDateTime, getLastOrNow_Year(false).ToShortDateString(), getLastOrNow_Year(false).AddYears(1).AddDays(-1).ToShortDateString());
            }

            return searchDateTime;
        }

        private string SortBy()
        {
            string SortBy = "ORDER BY {0} {1}";
            SortBy = string.Format(SortBy, ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);
            return SortBy;
        }

        protected void ddlStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        public string DrawChart()
        {
            // DateTime sNow = DateTime.Now;
            // string DayNow = sNow.DayOfWeek.ToString();
            DateTime LastSunday = getLastOrNow_SunDayOfWeek(false);
            DateTime NowSunday = getLastOrNow_SunDayOfWeek(true);
            // bool DidGet_NowSunday = false;
            //for (int i = -1; i > -15; i--)
            //{
            //    if (sNow.AddDays(i).DayOfWeek.ToString() == "Sunday")
            //    {
            //        if (DidGet_NowSunday == false)
            //        {
            //            NowSunday = sNow.AddDays(i);
            //            DidGet_NowSunday = true;
            //        }
            //        else
            //        {
            //            LastSunday = sNow.AddDays(i);
            //            break;
            //        }
            //    }


            //}

            string sql = @"
                    select Ngay, SUM(C003108) as DoanhThuNgay from (
                        select tbCuaHang.C007001  , tbDoanhSo.C003108 , (SELECT CONVERT (DATE, tbDoanhSo.UC00001)) as Ngay from   T0070 tbCuaHang
					    left join  T0031 tbDoanhSo
					    on tbCuaHang.C007001 = (select SUBSTRING(C003100, 1,CHARINDEX('-',C003100) - 1))
					    where tbDoanhSo.UC00001 >= convert(datetime,'" + LastSunday.ToShortDateString() + @"  00:00:00.001') and 
					    tbDoanhSo.UC00001 < = convert(datetime,'" + DateTime.Now.ToShortDateString() + @" 23:59:59.999')
                    ) TbResult
                    group by Ngay order by Ngay";

            DataSet ds = FunctionsUtils.Database.ExecuteQuery(sql);

            string arrValue = @"{'res':[";
            if (!FunctionsUtils.IsEmpty(ds))
            {
                for (int i = 0; i < 7; i++)
                {
                    DateTime sDay = Convert.ToDateTime("2115-05-05");
                    try
                    {
                        sDay = Convert.ToDateTime(ds.Tables[0].Rows[i]["Ngay"].ToString());
                    }
                    catch
                    { }

                    string value = "null";
                    try
                    {
                        value = ds.Tables[0].Rows[i]["DoanhThuNgay"].ToString();
                    }
                    catch
                    { }
                    string value_7 = "null";
                    try
                    {
                        value_7 = ds.Tables[0].Rows[i + 7]["DoanhThuNgay"].ToString();
                    }
                    catch
                    { }

                    if (i == 6)
                        arrValue += "{'Thu':'" + sDay.DayOfWeek.ToString() + "','ThisWeek':" + value + ",'LastWeek':" + value_7 + "}";
                    else
                        arrValue += "{'Thu':'" + sDay.DayOfWeek.ToString() + "','ThisWeek':" + value + ",'LastWeek':" + value_7 + "},";


                }
            }
            arrValue = arrValue + "]}";// 1 cột hoặc dòng


            return arrValue;
        }



        public DateTime getLastOrNow_SunDayOfWeek(bool LastOrNow)
        {
            // LastOrNow : true  trả về NowSunDayOfWeek , false trả về LastSunDayOfWeek
            DateTime sNow = DateTime.Now;
            string DayNow = sNow.DayOfWeek.ToString();
            DateTime LastSunday = DateTime.Now;
            DateTime NowSunday = DateTime.Now;
            bool DidGet_NowSunday = false;
            for (int i = -1; i > -15; i--)
            {
                if (sNow.DayOfWeek.ToString() == "Sunday")
                {
                    NowSunday = sNow;
                    LastSunday = sNow.AddDays(-7);
                }
                else
                {
                    if (sNow.AddDays(i).DayOfWeek.ToString() == "Sunday")
                    {
                        if (DidGet_NowSunday == false)
                        {
                            NowSunday = sNow.AddDays(i);
                            DidGet_NowSunday = true;
                        }
                        else
                        {
                            LastSunday = sNow.AddDays(i);
                            break;
                        }
                    }
                }


            }

            if (LastOrNow == true)
                return NowSunday;
            else
                return LastSunday;
        }


        public DateTime getLastOrNow_Month(bool LastOrNow)
        {
            DateTime sNow = DateTime.Now;

            if (LastOrNow == true)
                return new DateTime(sNow.Year, sNow.Month, 1);
            else
                return new DateTime(sNow.Year, sNow.AddMonths(-1).Month, 1);
        }


        public DateTime getLastOrNow_Year(bool LastOrNow)
        {
            DateTime sNow = DateTime.Now;

            if (LastOrNow == true)
                return new DateTime(sNow.Year, 1, 1);
            else
                return new DateTime(sNow.AddYears(-1).Year, 1, 1);
        }






    }
}